// tower.go
package main

import (
	"github.com/hajimehoshi/ebiten/v2"
	"github.com/hajimehoshi/ebiten/v2/vector"
	"image/color"
)

// TowerType 防御塔类型枚举
type TowerType int

const (
	TowerType1 TowerType = iota // 普通防御塔
	TowerType2                  // 远程防御塔
	TowerType3                  // 其他类型防御塔
)

// Tower 防御塔结构体
type Tower struct {
	Pos      Point         // 塔的位置
	Range    float64       // 攻击范围
	Damage   int           // 攻击伤害
	Cooldown int           // 攻击冷却
	Type     TowerType     // 塔类型
	Target   *Enemy        // 当前目标
	Image    *ebiten.Image // 防御塔图片
	Name     string        // 防御塔名字
}

// NewTower 创建一个新的防御塔
func NewTower(pos Point, towerType TowerType) *Tower {
	tower := &Tower{
		Pos:    pos,
		Type:   towerType,
		Target: nil,
	}

	switch towerType {
	case TowerType1:
		tower.Range = 150
		tower.Damage = 25
		tower.Cooldown = 15
		tower.Name = "Basic Tower"
	case TowerType2:
		tower.Range = 250 // 远程防御塔范围更大
		tower.Damage = 15 // 远程防御塔伤害降低
		tower.Cooldown = 20
		tower.Name = "Sniper Tower"
	case TowerType3:
		tower.Range = 150
		tower.Damage = 25
		tower.Cooldown = 15
		tower.Name = "Other Tower"
	}

	return tower
}

// Update 更新防御塔状态
// Tower 的 Update 方法添加扣血动画
func (t *Tower) Update(g *Game) {
	if t.Cooldown > 0 {
		t.Cooldown--
	}

	// 目标丢失或超出范围时重新寻找目标
	if t.Target == nil || t.Target.HP <= 0 || distance(t.Pos, t.Target.Pos) > t.Range {
		t.Target = g.findTarget(t)
	}

	// 发现目标且冷却完成时持续攻击
	if t.Target != nil && t.Cooldown <= 0 {
		g.bullets = append(g.bullets, &Bullet{
			Start:  t.Pos,
			Target: t.Target,
			Pos:    t.Pos,
			Speed:  bulletSpeed,
			Damage: t.Damage,
			Type:   t.Type, // 子弹类型
		})
		t.Cooldown = towerCooldown // 重置冷却时间

		// 扣血
		t.Target.HP -= t.Damage
	}
}

// Draw 绘制防御塔
func (t *Tower) Draw(screen *ebiten.Image) {
	towerColor := color.RGBA{B: 255, A: 255}
	if t.Type == TowerType2 {
		towerColor = color.RGBA{G: 255, A: 255} // 远程防御塔为绿色
	}

	vector.DrawFilledCircle(screen, float32(t.Pos.X), float32(t.Pos.Y), 20, towerColor, false)
	rangeColor := color.RGBA{B: 255, A: 64}
	vector.StrokeCircle(screen, float32(t.Pos.X), float32(t.Pos.Y), float32(t.Range), 2, rangeColor, false)
}
